package cn.framework.base.action;
  

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import cn.framework.model.UploadState;
  
public class BaseUploadFileAction extends FrameworkAction {   
	public static final String allAllowType="*.*";
    public static final int BUFFER_SIZE=16*1024;   
    // 用File数组来封装多个上传文件域对象   
    public File[] upload;   
    // 用String数组来封装多个上传文件名   
    public String[] uploadFileName;   
    // 用String数组来封装多个上传文件类型   
    public String[] uploadContentType;   
  
  
    // 保存文件的目录路径(通过依赖注入) 
    public String savePath="";   
    
    public BaseUploadFileAction(){
    	savePath="\\uploadFile";	
    }

    
  //文件复制
	public  boolean  copy(File src, File dst,int BUFFER_SIZE,String flag) {   
	
        boolean result=false;   
        InputStream in = null;   
        OutputStream out = null;   
        try {   
        	
            in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE);
        	double uploadSize=(double)in.available();
        	double uploadedSize=0;
        	double uploadPercent=0;
        	UploadState uploadState=new UploadState();
        	uploadState.setUploadSize(uploadSize);
            out = new BufferedOutputStream(new FileOutputStream(dst),   
                    BUFFER_SIZE);   
            byte[] buffer = new byte[BUFFER_SIZE];   
            int len = 0;   
            while ((len = in.read(buffer)) > 0) {   
                out.write(buffer, 0, len); 
                uploadedSize+=len;
                uploadPercent=uploadedSize*100/uploadSize;
                uploadState.setUploadedSize(uploadedSize);
                uploadState.setUploadPercent(uploadPercent);
                getSession().setAttribute(flag+"UploadState", uploadState);
            }   
            result=true;   
            getSession().removeAttribute(flag+"UploadState");
        } catch (Exception e) {   
            e.printStackTrace();   
            result=false;   
        } finally {   
            if (null != in) {   
                try {   
                    in.close();   
                } catch (IOException e) {   
                    e.printStackTrace();   
                }   
            }   
            if (null != out) {   
                try {   
                    out.close();   
                } catch (IOException e) {   
                    e.printStackTrace();   
                }   
            }   
        }   
        return result;   
    }   
	
	
	//上传文件方法
	  public List<String> uploadFile(String path,boolean isFullPath,String flag) throws IOException{
		  return uploadFile(path,isFullPath,false,flag,null);
	  }
	//上传文件方法
	  public List<String> uploadFile(String path,boolean isFullPath) throws IOException{
		  return uploadFile(path,isFullPath,false,"",null);
	  }
	  public List<String> uploadFile(String path,boolean isFullPath,boolean isPrototype)throws IOException{
		  return uploadFile(path,isFullPath,isPrototype,"",null);
	  }
	  
		//上传文件方法
	  public List<String> uploadFile(String path,boolean isFullPath,boolean isPrototype,String flag,String[] allowTypes) throws IOException{
   	   List<String> successFileList=new ArrayList<String>();
   	   if(allowTypes==null){
   		   allowTypes=new String[]{allAllowType};
   	   }
          // 处理每个要上传的文件   
          for (int i = 0; i < upload.length; i++) {   
              // 根据服务器的文件保存地址和原文件名创建目录文件全路径  
        	  String srcFilesInfo=uploadFileName[i].toString();
        	  //取得文件的后缀
        	  String  FileExtensions=srcFilesInfo.substring(srcFilesInfo.lastIndexOf("."),srcFilesInfo.length());
        	  if(!isAllowType(FileExtensions, allowTypes)){
        		  throw new IOException("上传文件格式有错误");
        	  }
        	  String fileName="";
        	  if(isPrototype){
        		  fileName=srcFilesInfo;
        	  }else{
        		  Calendar calendar=Calendar.getInstance();
        		  fileName=calendar.getTimeInMillis()+"-"+calendar.get(Calendar.HOUR_OF_DAY)+calendar.get(Calendar.MINUTE)+calendar.get(Calendar.SECOND)+i+FileExtensions;
        	  }
              String dstPath = getRealyPath(path) + "\\"+fileName;  
              File dstFile = new File(dstPath);   
              if(copy(upload[i], dstFile,BUFFER_SIZE,flag)){
            	  path=clearPath(path);
            	  if(isFullPath){
            		successFileList.add(path+fileName);  
            	  }else{
                    successFileList.add(fileName);
            	  }
              }  
              if(successFileList.size()<1){
              	throw new IOException();
              }
          } 
          return successFileList;
	  }
	  
	  public List<String> uploadFile(String path) throws IOException{
		  return uploadFile(path,false);
	  }
	  
	  public boolean isAllowType(String fileExtension,String[] allowTypes){
		  for (String allowType : allowTypes) {
			if(fileExtension.equals(allowType)
					||allowType.equals(allAllowType)){
				return true;
			}
		}
		  return false;
	  }
	  
	  //取得路径中的文件名
	 public List<String> getFileNames(String path){
		  File file=new File(getRealyPath(path));
		  List<String> resultList=new ArrayList<String>();
		  File[] files= file.listFiles();
		  for (File tempFile : files) {
			if(tempFile.isFile()){
				resultList.add(tempFile.getName());	
			}
		}
		  return resultList;
	  }
	  
	 //建立文件夹
	  public void createFold(String path){
	    	try{
	    		path=getRealyPath(path);
		    	File folder = new File(path); 
				if(!folder.exists()){
					FileUtils.forceMkdir(folder);
					logger.debug("建立文件夹:"+folder.getPath());
				}				
	    	}catch (Exception e) {
				e.printStackTrace();
			}
	    }
	  
	  /**删除文夹内所有文件
	     * @param path 目录
	     */
	    public boolean delFile(String path){
	    	boolean result=false;
	    	path=getRealyPath(path);
	        File file=new File(path);
	        if(file.isDirectory()){
	        	File[] files=file.listFiles();
	        	for (File targetFile : files) {
	        		result=targetFile.delete();
	        		if(result==false){
	        			return result;
	        		}
				}
 	        }else{
 	        	result=file.delete();
 	        }
	        return result;
	    }
	    
	    public boolean renameFile(String oldFilePath,String newFilePath){
	    	File oldFile=new File(oldFilePath);
	    	File newFile=new File(newFilePath);
	    	return oldFile.renameTo(newFile);
	    }
	  
	  //创建缩略图路径
	  public String createThumbPath(String abstractPath){
			String file=StringUtils.substringAfterLast(abstractPath, "\\");
			String fileType=StringUtils.substringAfterLast(abstractPath,".");
			String newPath=StringUtils.substringBeforeLast(abstractPath,".")+"-thumb."+fileType;  
			return newPath;
	  }
	  
	  public static String clearPath(String path){
	   path=StringUtils.replace(path,"\\","/");
	   path=StringUtils.replace(path,"\\\\","/");
	   return path;
	  }
	  
	  /*
	   *geter and seter 
	   *
	   * */
	public File[] getUpload() {
		return upload;
	}

	public void setUpload(File[] upload) {
		this.upload = upload;
	}

	public String[] getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(String[] uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String[] getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(String[] uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public String getSavePath() {
		return savePath;
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}

	public static int getBUFFER_SIZE() {
		return BUFFER_SIZE;
	}
	
	public UploadState getUploadState(HttpSession session,String flag){
		return (UploadState) session.getAttribute(flag+"UploadState");
	}

   
}  
